go to index

Machine Learning Competitions

read time 3 min read
Kaggle Intro Machine Learning

Machine Learning Competitions

机器学习竞赛是提高你的数据科学技能和衡量你的进步的好方法。

在下一个练习中,您将为Kaggle Learn用户创建并提交房价竞争的预测。

Introduction

在本练习中,您将为Kaggle竞赛创建并提交预测。然后你可以改进你的模型(例如,通过添加功能)来应用你所学到的知识,并在排行榜上上升。

首先运行下面的代码单元,以设置数据集的代码检查和文件路径。

python
# Set up code checking
from learntools.core import binder
binder.bind(globals())
from learntools.machine_learning.ex7 import *

# Set up filepaths
import os
if not os.path.exists("../input/train.csv"):
    os.symlink("../input/home-data-for-ml-course/train.csv", "../input/train.csv")  
    os.symlink("../input/home-data-for-ml-course/test.csv", "../input/test.csv") 

下面是到目前为止编写的一些代码。从重新运行它开始。

python
# Import helpful libraries
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split

# Load the data, and separate the target
iowa_file_path = '../input/train.csv'
home_data = pd.read_csv(iowa_file_path)
y = home_data.SalePrice

# Create X (After completing the exercise, you can return to modify this line!)
features = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlrSF', 'FullBath', 'BedroomAbvGr', 'TotRmsAbvGrd']

# Select columns corresponding to features, and preview the data
X = home_data[features]
X.head()

# Split into validation and training data
train_X, val_X, train_y, val_y = train_test_split(X, y, random_state=1)

# Define a random forest model
rf_model = RandomForestRegressor(random_state=1)
rf_model.fit(train_X, train_y)
rf_val_predictions = rf_model.predict(val_X)
rf_val_mae = mean_absolute_error(rf_val_predictions, val_y)

print("Validation MAE for Random Forest Model: {:,.0f}".format(rf_val_mae))

Train a model for the competition

上面的代码单元在train_X和train_y上训练随机森林模型。

使用下面的代码单元构建一个随机森林模型,并在所有X和y上训练它。

python
# To improve accuracy, create a new Random Forest model which you will train on all training data
rf_model_on_full_data = ____

# fit rf_model_on_full_data on all data from the training data
____

现在,读取“测试”数据文件,并应用您的模型进行预测。

python
# path to file you will use for predictions
test_data_path = '../input/test.csv'

# read test data file using pandas
test_data = ____

# create test_X which comes from test_data but includes only the columns you used for prediction.
# The list of columns is stored in a variable called features
test_X = ____

# make predictions which we will submit. 
test_preds = ____

在提交之前,运行检查以确保test_preds具有正确的格式。

python
# Check your answer (To get credit for completing the exercise, you must get a "Correct" result!)
step_1.check()
# step_1.solution()

Generate a submission

运行下面的代码单元格,生成一个CSV文件,其中包含您的预测,您可以使用该预测提交给竞赛。

python
# Run the code to save predictions in the format used for competition scoring

output = pd.DataFrame({'Id': test_data.Id,
                       'SalePrice': test_preds})
output.to_csv('submission.csv', index=False)

Submit to the competition